#最后一步识别人脸
#-*- coding: utf-8 -*-

import cv2
import sys
import gc
from face_train_use_keras import Model
import tensorflow as tf

if __name__ == '__main__':

        
    #加载模型
    model = Model()
    model.load_model(file_path = 'C:/Users/LCG/Desktop/data/test/me.face.model5.h5')
              
    #框住人脸的矩形边框颜色       
    color = (0, 255, 255)
    
    #捕获指定摄像头的实时视频流
    cap = cv2.VideoCapture(0)
    
    #人脸识别分类器本地存储路径
    cascade_path = "C:/Users/LCG/Desktop/data/test/haarcascade_frontalface_alt2.xml"
    
    #循环检测识别人脸
    while cap.isOpened():
        ret, frame = cap.read()   #读取一帧视频


        #图像灰化，降低计算复杂度
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        
        #使用人脸识别分类器，读入分类器
        cascade = cv2.CascadeClassifier(cascade_path)                

        #利用分类器识别出哪个区域为人脸
        faceRects = cascade.detectMultiScale(gray, scaleFactor = 1.2, minNeighbors = 3, minSize = (16, 16))        
        if len(faceRects) > 0:                 
            for faceRect in faceRects: 
                x, y, w, h = faceRect
                
                #截取脸部图像提交给模型识别这是谁
                image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
                cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, thickness = 2)
                faceID = model.face_predict(image)   
                print(faceID)
                #如果是“我”
                if faceID == 0:                                                        
                    cv2.putText(frame, "this is cat", (x+30, y+30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2)
                elif faceID == 1:
                    cv2.putText(frame, "this is dog", (x+30, y+30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2)
                # elif faceID == 2:
                #     cv2.putText(frame, "this is xue", (x + 30, y + 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2)
                # else:
                #     cv2.putText(frame, "this is me", (x + 30, y + 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2)

        cv2.imshow("classify me", frame)
        
        #writer = tf.summary.FileWriter("log_1",tf.get_default_graph());
        #writer.close();

         #等待10毫秒看是否有按键输入
        k = cv2.waitKey(10)
        #如果输入q则退出循环
        if k & 0xFF == ord('q'):
            break

    #释放摄像头并销毁所有窗口
    cap.release()
    cv2.destroyAllWindows()
